import json

import requests  # 网络请求
import base64
from django.shortcuts import HttpResponse


class SpiderHaiJiaoSheQu:
    # 初始化
    def __init__(self):
        self.__Domain = "https://www.hj87d29.top/"
        self.__headers = {
            'user-agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1',
        }
    
    # 海角数据加密破解函数
    def __HaiJiaoEncryptionCracking(self, EncryptionData: str) -> list:
        global encodestr
        for i in range(3):
            if i == 0:
                encodestr = base64.b64decode(EncryptionData)
            else:
                encodestr = base64.b64decode(encodestr)
        return json.loads(encodestr.decode())
    
    # 获取帖子数据
    def GetHaiJiaoNewsList(self, Page=1, BanKuaiId=1):
        Params = {
            "page": Page
        }
        ApiUrl = ""
        # 板块的api链接
        BanKuaiUrlList = [
            "api/topic/hot/topics",  # 首页
            "api/topic/node/news"  # 新闻
        ]
        if BanKuaiId == 1:
            ApiUrl = BanKuaiUrlList[0]
        elif BanKuaiId == 2:
            ApiUrl = BanKuaiUrlList[1]
        else:
            return []
        response = requests.get(url=self.__Domain + ApiUrl, headers=self.__headers, params=Params).json()
        data = self.__HaiJiaoEncryptionCracking(response['data'])
        return data
    
    # 获取帖子详情数据
    def GetHaiJiaoNewsInfo(self, Pid):
        SpiderUrl = self.__Domain + f"api/topic/{Pid}"
        response = requests.get(url=SpiderUrl, headers=self.__headers).json()
        data = self.__HaiJiaoEncryptionCracking(EncryptionData=response['data'])
        return data
    
    # 获取帖子的评论
    def GetHaiJiaoCommit(self, Pid, Page=1):
        SpiderUrl = self.__Domain + f"api/comment/reply_list"
        Params = {
            "page": Page,
            "sort": "asc",
            "topic_id": Pid,
            "search_type": 0,
            "user_id": 0
        }
        response = requests.get(url=SpiderUrl, headers=self.__headers, params=Params).json()
        data = self.__HaiJiaoEncryptionCracking(response['data'])
        return data
    
    # 搜索
    def GetHaiJiaoSearch(self, SearchText, Page=1):
        SpiderUrl = self.__Domain + "api/topic/search"
        Params = {
            "key": SearchText,
            "node_id": 0,
            "page": Page
        }
        response = requests.post(url=SpiderUrl, headers=self.__headers, data=Params).json()
        data = self.__HaiJiaoEncryptionCracking(response['data'])
        return data
    
    # 单独获取m3u8免费视频
    def GetHaiJiaoMFVideo(self, ImageID, TzID):
        SpiderUrl = self.__Domain + "api/attachment"
        headers = {
            'x-user-id': '171297706501',
            'x-user-token': '2c761d2bf3434ae09fcc0502aa18d42a',
        }
        json_data = {
            'id': int(ImageID),
            'resource_type': 'topic',
            'resource_id': int(TzID),
            'line': '',
        }
        response = requests.post(url=SpiderUrl, headers=headers, json=json_data).json()['data']
        res = self.__HaiJiaoEncryptionCracking(response)
        res['remoteUrl'] = self.__Domain + res['remoteUrl'][1::]
        return res


sp = SpiderHaiJiaoSheQu()


# 获取帖子列表
def GetCardList(request):
    if request.method == 'GET':
        try:
            Page = request.GET.get("Page")
            BanKuaiId = request.GET.get("BanKuaiId")
            if BanKuaiId is None:
                BanKuaiId = 1
            if Page is None:
                Page = 1
            res = sp.GetHaiJiaoNewsList(int(Page), int(BanKuaiId))
            return HttpResponse(json.dumps(res))
        except Exception as e:
            return HttpResponse("服务器错误，如管理员没有急救修复可添加开发者微信进行询问，免费至上！", status=500)
    else:
        return HttpResponse("不支持的请求方式，请求GET方式进行请求", status=501)


# 获取帖子的详情
def GetCardInfo(request):
    try:
        if request.method == 'GET':
            Pid = int(request.GET.get("Pid"))
            res = sp.GetHaiJiaoNewsInfo(Pid=Pid)
            return HttpResponse(json.dumps(res), status=200)
    except Exception as e:
        return HttpResponse("服务器错误，如管理员没有急救修复可添加开发者微信进行询问，免费至上！", status=500)


# 获取帖子的评论
def GetCardCommit(request):
    try:
        if request.method == 'GET':
            Pid = int(request.GET.get("Pid"))
            Page = int(request.GET.get("Page"))
            res = sp.GetHaiJiaoCommit(Pid=Pid, Page=Page)
            return HttpResponse(json.dumps(res), status=200)
    except Exception as e:
        return HttpResponse("服务器错误，如管理员没有急救修复可添加开发者微信进行询问，免费至上！", status=500)


# 搜索
def GetHaiJiaoCardSearchText(request):
    try:
        if request.method == 'GET':
            SearchText = request.GET.get("SearchText")
            Page = request.GET.get("Page")
            if Page is None:
                Page = 1
            res = sp.GetHaiJiaoSearch(SearchText=SearchText, Page=Page)
            return HttpResponse(json.dumps(res), status=200)
        else:
            return HttpResponse("走完")
    
    except Exception as e:
        return HttpResponse("服务器错误，如管理员没有急救修复可添加开发者微信进行询问，免费至上！", status=500)


# 根据id获取视频
def GetHaiJiaoMFVideo(request):
    try:
        if request.method == 'GET':
            ImageID = request.GET.get("ImageID")
            TzID = request.GET.get("TzID")
            if ImageID is None:
                ImageID = 17815685
            res = sp.GetHaiJiaoMFVideo(ImageID=ImageID, TzID=TzID)
            return HttpResponse(json.dumps(res), status=200)
        else:
            return HttpResponse("走完")
    
    except Exception as e:
        return HttpResponse("服务器错误，如管理员没有急救修复可添加开发者微信进行询问，免费至上！", status=500)


if __name__ == '__main__':
    sp.GetHaiJiaoMFVideo(ImageID=7815685, TzID=1292405)
